<template>
  <div class="setting-content inside-comment">
    <el-scrollbar height="calc(100vh - 170px)">
      <h2 class="setting-header">
        <strong>学员管理</strong>
      </h2>
      <div class="top-info">
        <SearchCmp v-if="searchCmpArray.length && departTree.value != []" :searchCmpArray="searchCmpArray" :searchForm="queryData"  @onSubmit="getTableData" />
        <div class="right-add">
          <el-button type="primary" @click="addDrawer">添加学员</el-button>
          <el-button type="primary" @click="importStudent">批量导入</el-button>
        </div>
      </div>
      <RuifoxTable
        v-loading="tableLoading"
        :table-data="tableData"
        :field-list="fieldList"
        :default-index="true"
        :default-checkbox="true"
        :lazy="true"
      >
        <template #default-checkbox="{ element }">
          <div class="table-div-check">
            <el-checkbox
              class="unmover"
              v-model="element.checked"
              @change="handleCheckTable(element.id)"
              size=""
            />
          </div>
        </template>
        <!-- 状态  -->
        <template #state="{ element }"> 
          <div>
            <el-tag v-if="element.state == 0" type="primary">正常</el-tag>
            <el-tag v-else type="success" >禁用</el-tag>
          </div>
        </template>
        
        <!-- 身份认证  -->
        <template #identificationVerify="{ element }"> 
          <div>
            <el-tag v-if="element.identificationVerify == true" type="primary">已认证</el-tag>
            <el-tag v-else type="warning">未认证</el-tag>
          </div>
        </template>
        <!-- 有效时间  -->
        <template #effectiveTime="{ element }" >
          <div class="item-info" v-if="element.effectiveTime && element.effectiveTime != 0">{{ formatDate(element.effectiveTime,"yyyy-MM-dd") }}</div>
        </template>

        <template #options="{ element }">
          <div class="table-td-option unmover">
            <el-button
              type="primary"
              link
              @click="showDrawer(element)"
            >
              编辑
            </el-button>
            <!-- <el-button
              type="danger"
              link
              @click="remove(element)"
            >
              删除
            </el-button> -->
          </div>
        </template>
      
      </RuifoxTable>
      <PaginationView
        :isAffix = "false"
        :total="queryData.total"
        :pageSize="queryData.pageSize"
        :currentPage="queryData.currentPage"
        :allChoose="isAllChooseBtn"
        :pageChoose="isPageChooseBtn"
        :options="batchOptions"
        :checkedNum="checkedNum"
        :canChoose="queryData.total > 0"
        @changeSize="handleSizeChange"
        @currentChange="handleCurrentChange"
        @changePageChoose="handlePageChoose"
        @changeAllChoose="handleAllChoose"
        @invertChoose="handleInvertChoose"
        @checkOption="handleBatchOptions"
        @refreshList="getTableData"
        @cancelChoose="handleResetPagination"
        v-if="tableData.length > 0"
      />
    </el-scrollbar>
    <!-- 添加学员  -->
    <el-dialog
      v-model="studentDrawer"
      :title="drawTitle"
      size="450px"
      class="enterprise-drawer"
    >
      <template #default>
        <el-form ref="userFormRef" :model="formData" :rules="rules" label-width="100px">
          <el-form-item label="学员名称" prop="realName">
            <el-input v-model="formData.realName" placeholder="请输入学员名称" />
          </el-form-item>
          <el-form-item label="昵称">
            <el-input v-model="formData.name" placeholder="请输入学员昵称" />
          </el-form-item>
          <el-form-item label="手机号" prop="account">
            <el-input v-model="formData.account" placeholder="请输入手机号" />
          </el-form-item>
          <el-form-item label="身份证号" prop="identificationNumber">
            <el-input v-model="formData.identificationNumber" placeholder="请输入身份证号" />
          </el-form-item>
          <!-- 选择部门  -->
          <el-form-item label="选择部门" prop="permanent">
            <el-cascader :options="departTree" v-model="formData.departId" clearable :show-all-levels="false" popper-class="pid-cascader" placeholder="请选择部门" @change="handleChange">
              <template #default="{ data }">
                <p>{{data.label}}</p>
              </template>
            </el-cascader>
          </el-form-item>
          <!-- 选择分组  -->
          <!-- <el-form-item label="选择分组" prop="permanent">
            <el-select
              v-model="formData.groupId"
              style="width: 200px"
              @change="handleReplyChange"
            >
              <el-option
                v-for="item in groupList"
                :key="item.value"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item> -->
          <el-form-item label="入职时间" prop="joinTime" >
            <el-date-picker 
              v-model="formData.joinTime"
              type="datetime"
              placeholder="选择入职时间"
            />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-button @click="resetPassword" v-show="!isResetPass && userFormWay !== 1">重置密码</el-button>
            <el-input v-model="formData.password" readonly v-show="isResetPass || userFormWay === 1">
              <template #append v-if="userFormWay !== 1">
                <div class="done-reset-password" v-if="isResetPass">
                  <i class="iconfont">&#xe655;</i>
                  已重置
                </div>
              </template>
              <template #append v-else>
                <div class="reset-password" @click="initPassword" v-if="!isInitPass">生成密码</div>
                <div class="done-reset-password" v-if="isInitPass">
                  <i class="iconfont">&#xe655;</i>
                  已生成
                </div>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="是否长期有效" prop="permanent">
            <el-switch v-model="formData.permanent" />
          </el-form-item>
          <el-form-item label="有效时间" prop="effectiveTime" >
            <el-date-picker 
              v-model="formData.effectiveTime"
              type="effectiveTime"
              placeholder="选择有效时间"
            />
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="studentDrawer = false">取消</el-button>
          <el-button type="primary" @click="confirmClick">确认</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 加入部门  -->
    <el-dialog
      v-model="joinDepartDrawer"
      title="选择加入部门"
      width="450px"
      class="enterprise-drawer"
    >
      <el-form :rules="rules" label-width="70px">
        <el-form-item label="选择部门" prop="permanent">
          <el-cascader :options="departTree" v-model="theDepartId" :show-all-levels="false" popper-class="pid-cascader" placeholder="请选择部门" @change="handleChange">
            <template #default="{ data }">
              <p>{{data.label}}</p>
            </template>
          </el-cascader>
          <!-- <el-tree-select
            v-model="theDepartId"
            :data="departTree"
            filterable
            clearable
            placeholder="请选择"
            style="width: 320px;"
            check-strictly
            :render-after-expand="false"
            ref="treeSelectRef"
            default-expand-all
          /> -->
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="joinDepartDrawer = false">取消</el-button>
          <el-button type="primary" @click="confirmDepart">确认</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 加入群组  -->
    <el-dialog
      v-model="joinGroupDrawer"
      title="选择加入群组"
      width="450px"
      class="enterprise-drawer"
    >
      <el-form :rules="rules" label-width="70px">
        <el-form-item label="选择分组" prop="permanent">
          <el-select
            v-model="theGroup"
            style="width: 200px"
            @change="handleReplyChange"
          >
            <el-option
              v-for="item in groupList"
              :key="item.value"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="joinGroupDrawer = false">取消</el-button>
          <el-button type="primary" @click="confirmGroup">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { pagingUser } from '@/api/student'
import { tableList as mixTable } from '@ruifox-cms/utils'
import { formatDate } from '@/utils/tools'
import { saveUserUser, getUserInfoWithoutDesensitize } from "@/api/student"
import { ElMessage } from 'element-plus'
import { changeDepart, getDepartTree } from "@/api/depart";
import { addUserGroup, pagingGroup } from "@/api/group";
import { useStore } from 'vuex' 

const store = useStore();
const {
  queryData,
  tableData,
  tableLoading,
  checkedNum,
  isAllChooseBtn,
  isPageChooseBtn,
  checkedList,
  isAllSearch,
  getTableData,
  // handleSearch,
  handleCurrentChange,
  handleSizeChange,
  handlePageChoose,
  handleAllChoose,
  handleInvertChoose,
  handleCheckTable,
  handleResetPagination,
} = mixTable({
  getListApi: pagingUser,
});
const defaultQuery = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 2,
  sort: "",
  order: "joinTime",
  checked: true,
  needToSort: true,
  sortArray: [],
  orderArray: [],
  realName: "",
  identificationNumber: "",
  departId: "",
  joinTime: "",
  effectiveTime: "",
  cohortIds: [],
  departIds: [],
  orderByStatement: "",
  statement: ""
});

Object.assign(queryData, defaultQuery);
watch(() => queryData, (newVal) => {
  if (!Array.isArray(newVal.cohortIds)) {
    queryData.cohortIds = [newVal.cohortIds]
  }
}, { deep: true });

// const tableData = ref([])
// const getTableData = async () => {
//   const res = await pagingUser(queryData)
//   if(res.code == 20000){
//     tableData.value = res.data.list
//     queryData.total = 10
//   }
// }
const rules = {
  realName: [{ required: true, message: '请输入学员姓名', trigger: 'blur' }],
  account: [
    { required: true, message: '请输入学员手机号', trigger: 'blur' },
    { 
      pattern: /^1[3-9]\d{9}$/, 
      message: '请输入正确的手机号格式', 
      trigger: 'blur' 
    }
  ],
  identificationNumber: [
    { required: true, message: '请输入学员身份证', trigger: 'blur' },
    { 
      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, 
      message: '请输入正确的身份证号码', 
      trigger: 'blur' 
    }
  ],
  // joinTime: [{ required: true, message: '请选择学员入职时间', trigger: 'change' }],
}
//添加用户
const delaultStudent = reactive({
  id: "",
  pid: 0,
  account: "",
  password: "",
  name: "",
  introduction: "",
  avatar: "",
  appKey: "",
  appSecret: "",
  mfa: 0,
  fce: 0,
  validTime: "",
  state: 0,
  realName: "",
  identificationNumber: "",
  identificationPhoto: "",
  identificationVerify: true,
  departId: "",
  groupId: store.state.base.userInfo.groupId,
  joinTime: "",
  permanent: true,
  effectiveTime: "",
  updateMainUserInfo: true
})
const formData = ref(delaultStudent)

const studentDrawer = ref(false);
const drawTitle = ref("");
const addDrawer = () => {
  drawTitle.value = "添加学员";
  studentDrawer.value = true;
  formData.value = { ...delaultStudent }
}
//编辑
const showDrawer = async (row) => {
  drawTitle.value = "编辑学员";
  studentDrawer.value = true;
  formData.value = {...row};
  formData.value.updateMainUserInfo = true;
  console.log("formData.value00",formData.value);

  if(formData.value.joinTime && formData.value.joinTime != ""){
    formData.value.joinTime = formData.value.joinTime.replace(' ', 'T');
  }
  //根据用户请求详细数据
  const res = await getUserInfoWithoutDesensitize({userId: row.id})
  if(res.code === 20000){
    formData.value.realName = res.data.realName
    formData.value.identificationNumber = res.data.identificationNumber
  }
  console.log("formData.value",formData.value);
};

//提交用户
const userFormRef = ref(null);
const confirmClick = async () => {
  // 校验表单
  if (!userFormRef.value) return;
  try {
    const valid = await validateForm();
    if (!valid) return;
    if(formData.value.joinTime){
      formData.value.joinTime = formatDate(formData.value.joinTime, "YYYY-MM-DD HH:mm:ss");
    }
    if(formData.value.effectiveTime){
      formData.value.effectiveTime = formatDate(formData.value.effectiveTime, "YYYY-MM-DD HH:mm:ss");
    }
    if(formData.value.departId && formData.value.departId != "")
    if (Array.isArray(formData.value.departId)) {
      formData.value.departId = formData.value.departId[formData.value.departId.length - 1]
    }
    //根据标题判断是添加还是修改
    if (drawTitle.value == "添加学员") {
      const res = await saveUserUser(formData.value)
      if (res.code === 20000) {
        ElMessage.success("添加成功");
      }
    } else if (drawTitle.value == "编辑学员") {
      const res = await saveUserUser(formData.value)
      if (res.code === 20000) {
        ElMessage.success("修改成功");
      }
    }
    studentDrawer.value = false;
    isResetPass.value = false;
    getTableData()
  } catch (error) {
    console.error("An error occurred:", error);
  }
};

//检查表单
const validateForm = () => {
  return new Promise((resolve) => {
    userFormRef.value.validate((isValid, fields) => {
      if (isValid) {
        console.log("submit!");
        resolve(true);
      } else {
        console.log("error submit!", fields);
        resolve(false);
      }
    });
  });
};

//重置密码
const isResetPass = ref(false)
const isInitPass = ref(false)

const resetPassword = () => {
  isResetPass.value = true
  formData.value.send_note = true
  formData.value.password = generatePassword(10)
  if (rules.value) {
    rules.value.validateField('password')
  }
}
const initPassword = () => {
  isInitPass.value = true
  formData.value.send_note = true
  formData.value.password = generatePassword(10)
  if (rules.value) {
    rules.value.validateField('password')
  }
}
const generatePassword = (length) => {
  const lowercase = 'abcdefghijklmnopqrstuvwxyz'
  const uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  const numbers = '0123456789'
  const special = '!@#$%^&*'
  
  // 所有可用字符
  const allChars = lowercase + uppercase + numbers + special
  
  // 确保至少包含三种字符类型
  let password = ''
  const charTypes = [lowercase, uppercase, numbers, special]
  
  // 随机选择3种字符类型
  const selectedTypes = charTypes
    .sort(() => Math.random() - 0.5)
    .slice(0, 3)
  
  // 从每种选中的类型中至少选择一个字符
  selectedTypes.forEach(type => {
    password += type.charAt(Math.floor(Math.random() * type.length))
  })
  
  // 填充剩余长度
  while (password.length < length) {
    password += allChars.charAt(Math.floor(Math.random() * allChars.length))
  }

  return password
    .split('')
    .sort(() => Math.random() - 0.5)
    .join('')
}

//获取部门树
const departTree = ref([]);
const transformData = (data) => {
  return data.map(item => {
    const transformedItem = {
      value: item.id,
      label: item.name
    };

    if (item.children && item.children.length > 0) {
      transformedItem.children = transformData(item.children);
    }

    return transformedItem;
  });
};
const getDepartData = async () => {
  const res = await getDepartTree({departId: "root"});
  if (res.code === 20000) {
    departTree.value = transformData(res.data.children)
    searchCmpArray.value[1].options = departTree.value
  }
};

const theDepartId = ref("");

//获取分组
const groupList = ref([])
const theGroup = ref("");
const getGroupData = async () => {
  const res = await pagingGroup({ 
    currentPage: 1,
    pageSize: 100
  });
  groupList.value = res.data.list;
  let newList = groupList.value.map(item => ({
      value: item.id,
      label: item.name,
    }));
  searchCmpArray.value[2].options = newList
};

//********批量操作
//批量加入部门 一人仅限加入一个
const joinDepartDrawer = ref(false);
const handleBatchDepart = async () => {
  joinDepartDrawer.value = true;
}
//更改部门
const confirmDepart = async () => {
  if (theDepartId.value == "") {
    ElMessage.warning("请选择部门");
    return
  }
  let idlist = []
  idlist = checkedList.value
  let departId = ""
  if (Array.isArray(theDepartId.value)) {
    theDepartId.value = theDepartId.value[theDepartId.value.length - 1]
  }
  departId = theDepartId.value
  console.log("departId",departId);
  let data = {
    userIds: idlist,
    targetDepartId: departId,
  };
  console.log(data);
  
  changeDepart(data).then((res) => {
    if (res.code === 20000) {
      ElMessage.success("更新成功");
      getTableData();
      isAllChooseBtn.value = false;
      checkedList.value = [];
      isAllSearch.value = false;
      joinDepartDrawer.value = false
    }
  });
  theDepartId.value = ""
}
//更改群组
const confirmGroup = () => {
  if (theGroup.value == "") {
    ElMessage.warning("请选择分组");
    return
  }
  let idlist = []
  idlist = checkedList.value
  let groupId = ""
  groupId = theGroup.value
  console.log("groupId",groupId);
  let data = {
    userIds: idlist,
    cohortId: groupId,
  };
  addUserGroup(data).then((res) => {
    if (res.code === 20000) {
      ElMessage.success("更新成功");
      getTableData();
      isAllChooseBtn.value = false;
      checkedList.value = [];
      isAllSearch.value = false;
      joinGroupDrawer.value = false
    }
  });
  theGroup.value = ""
}
//批量加入群组 一人可加多个
const joinGroupDrawer = ref(false);
const handleBatchGroup = async () => {
  joinGroupDrawer.value = true;
}
// 批量操作
const batchOptions = ref([
  { name: "加入部门", value: "addDepart", icon: "&#xe6ed;" },
  { name: "加入群组", value: "addGroup", icon: "&#xe6e4;" },
]);
const handleBatchOptions = (data) => {
  if (data === "addDepart") {
    handleBatchDepart();
  } else if (data === "addGroup") {
    handleBatchGroup();
  } 
};

//搜索条件
// 用户筛选字段
// const timeOption = ref([
//   { label: "待回复", value: 0 },
//   { label: "已回复", value: 1 },
// ]);

const orderOption = ref([
  { label: "正序", value: 0 },
  { label: "倒序", value: 1 },
]);

const searchCmpArray = ref([
  { label: '按名称搜索', key: 'realName'},
  { label: '部门', key: 'departIds', form_type: 'cascader', options: departTree.value },
  { label: '群组', key: 'cohortIds', form_type: 'select', options: groupList.value,  props: { label: 'name', value: 'id' }},
  { label: '排序', key: 'sort', form_type: 'select', options: orderOption.value }
])

//表格展示字段
const fieldList = ref([
  {
    title: "姓名",
    name: "realName",
  },
  {
    title: "昵称",
    name: "name",
  },
  {
    title: "身份证号",
    name: "identificationNumber",
  },
  {
    title: "手机号",
    name: "account",
  },
  {
    title: "部门",
    name: "departName",
  },
  {
    title: "群组",
    name: "groupId",
  },
  {
    title: "状态",
    name: "state",
  },
  {
    title: "身份认证",
    name: "identificationVerify",
  },
  {
    title: "有效时间",
    name: "effectiveTime",
  },
  {
    title: "操作",
    name: "options",
    width: 150,
  },
]);

// beforeMounted(() => {
//   getDepartData();
// });
onMounted(async() => {
  await getDepartData();
  await getGroupData();
  await getTableData();
});
</script>
<style scoped lang="scss">
.top-info{
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}
</style>